/*
 * @(#)PrimeUtil.java	1.0 Apr 26, 2008
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.math.prime;

import org.eoti.math.MathUtil;

import java.math.BigInteger;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.util.*;

public class PrimeUtil
{
	protected static BigInteger BigIntegerTWO = BigInteger.valueOf(2);

	public static void main(String[] args)
	{
		BigInteger value = new BigInteger(args[0]);
		long start = System.nanoTime();
		boolean isPrime = isPrime(value);
		long end = System.nanoTime();
		System.out.println("Found out that " + value + (isPrime?" is ":" is not ")+"prime in " + NANOSECONDS.toMillis(end-start) + " ms");

		start = System.nanoTime();
		Collection<PrimeFactor> factors = MathUtil.factor(value);
		end = System.nanoTime();
		System.out.println("Found the factors of " + value + " in " + NANOSECONDS.toMillis(end-start) + " ms");
		for(PrimeFactor factor : factors)
			System.out.println("\t"+factor);
		System.out.println("Let's verify");
		BigInteger total = BigInteger.ONE;
		for(PrimeFactor factor : factors)
			total = total.multiply(factor.getValue());
		System.out.println("Total value: " + total);
		if(total.equals(value))
			System.out.println("VALIDATED");
		else
			System.out.println("Ooops....");
	}

	public static boolean isPrime(BigInteger value)
	{
		if(value.signum() < 0) return false; // don't accept negatives...?

		BigInteger n = value.subtract(BigInteger.ONE);
		return ((MathUtil.factorial(n)).mod(value)).equals(n);
	}
}
